﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GameProtocol.Common;
using GameProtocol.Dto;
using GameProtocol.Protocol;
using NetCommon;
using RPGGameServer.Biz;
using RPGGameServer.Tools;
using ServerFrame;

namespace RPGGameServer.Logic
{
    class LoginHandler : IHandler
    {
        private AccountBiz accountBiz = BizManager.Get<AccountBiz>();

        public Protocal Protocal => Protocal.Login;

        
        public void ClientClose(UserToken token, string error)
        {
            
        }

        /// <summary>
        /// 消息派发
        /// </summary>
        /// <param name="token"></param>
        /// <param name="error"></param>
        public void ReceiveMessage(UserToken token, NetModel model)
        {
            switch (model.commond)
            {
                case LoginProtocol.C2S_Login:
                    Login(token, model.Get<AccountDto>());
                    break;
                case LoginProtocol.C2S_Register:
                    Register(token, model.Get<AccountDto>());
                    break;
                case LoginProtocol.C2S_CreateUser:
                    break;
                default:
                    break;
            }
        }

        /// <summary>
        /// 注册（创建账号）
        /// </summary>
        /// <param name="token"></param>
        /// <param name="dto"></param>
        public void Register(UserToken token, AccountDto dto)
        {
            ExcuteManager.Excute(delegate ()
            {
                accountBiz.Create(token, dto);
            });
        }

        /// <summary>
        /// 登录的方法
        /// </summary>
        /// <param name="token"></param>
        /// <param name="accountDto"></param>
        private void Login(UserToken token, AccountDto accountDto)
        {
            //Console.WriteLine("逻辑层调用事务层执行登录逻辑");
            ExcuteManager.Excute(delegate ()
            {
                ErrorCode error = accountBiz.Login(token, accountDto.account, accountDto.password);
                if (error == ErrorCode.Success)
                {
                    // 通知客户端登录成功
                    ExUserToken.Send(token, Protocal.Login, LoginProtocol.S2C_Login);
                    token.Send(Protocal.Login, LoginProtocol.S2C_Login);

                }
                else
                {
                    //错误类型发送给客户端
                    ExUserToken.Send(token, error);
                    token.Send(error);

                }
            });
        }
    }
}
